const { workerData, parentPort } = require('worker_threads')
const fs = require('fs')
const readline = require('readline')

const { isPm2Hosting, logFilePath, start, end, timeRange } = workerData

// 用于存储包下载量的对象
const downloadStats = {}

// 统计不同时间段的包下载量
const periodStats = {
  lastWeek: {}, // 最近一周
  thisWeek: {}, // 本周
  lastMonth: {}, // 最近一月
  thisMonth: {} // 本月
}

// 正则表达式匹配日志行(兼容verdaccio和PM2,同时匹配不含时间戳原日志)
const pattern1 = /http\s+<--\s+(200|304),\s+user:\s+(\w+)\(([\d.]+)\),\s+req:\s+'GET \/([^']+)',\s+bytes:\s+(\d+)\/(\d+)/ // verdaccio
const pattern2 = /http\s+---\s+(200|304),\s+user:\s+(\w+)\(([\d.]+)\),\s+req:\s+'GET \/([^']+)',\s+bytes:\s+(\d+)\/(\d+)/ // PM2
const pattern3 = /\[(.*?)\] http\s+<--\s+(200|304),\s+user:\s+(\w+)\(([\d.]+)\),\s+req:\s+'GET \/([^']+)',\s+bytes:\s+(\d+)\/(\d+)/ // verdaccio
const pattern4 = /\[(.*?)\]http\s+---\s+(200|304),\s+user:\s+(\w+)\(([\d.]+)\),\s+req:\s+'GET \/([^']+)',\s+bytes:\s+(\d+)\/(\d+)/ // PM2

// const log_Pattern = isPm2Hosting ? pattern2 : pattern1
// const log_TimePattern = isPm2Hosting ? pattern4 : pattern3

const log_Pattern = isPm2Hosting
  ? /requested 'GET \/([^']+)'/ // PM2
  : /requested 'GET \/([^']+)'/ // verdaccio
const log_TimePattern = isPm2Hosting
  ? /\[(.*?)\]http --- .* requested 'GET \/([^']+)'/ // PM2
  : /\[(.*?)\] .* requested 'GET \/([^']+)'/ // verdaccio

// 创建逐行读取日志的接口
const fileStream = fs.createReadStream(logFilePath, { start, end })
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity })

// 逐行读取日志
rl.on('line', (line) => {
  // if (line.includes('200') || line.includes('304')) {
  if (line.includes('requested')) {
    const match = line.match(log_Pattern)
    if (match) {
      const packageName = match[1]

      // 统计总数
      downloadStats[packageName] = (downloadStats[packageName] || 0) + 1
    }

    const matchTime = line.match(log_TimePattern)

    if (matchTime) {
      const logTimeStr = matchTime[1]
      const packageName = matchTime[2]

      // 解析日志时间
      const logTime = new Date(logTimeStr).getTime()

      if (logTime >= timeRange.agoTime[0]) {
        periodStats.lastWeek[packageName] = (periodStats.lastWeek[packageName] || 0) + 1
      }

      if (logTime >= timeRange.agoTime[1]) {
        periodStats.lastMonth[packageName] = (periodStats.lastMonth[packageName] || 0) + 1
      }

      if (logTime >= timeRange.weekTime[0] && logTime <= timeRange.weekTime[1]) {
        periodStats.thisWeek[packageName] = (periodStats.thisWeek[packageName] || 0) + 1
      }

      if (logTime >= timeRange.monthTime[0] && logTime <= timeRange.monthTime[1]) {
        periodStats.thisMonth[packageName] = (periodStats.thisMonth[packageName] || 0) + 1
      }
    }
  }
})

// 读取完成后返回结果
rl.on('close', () => {
  parentPort.postMessage({
    downloadStats,
    ...periodStats
  })
})

// 捕获错误并返回空结果
rl.on('error', (error) => {
  parentPort.postMessage(null)
})
